package com.blueflamedev.performance
{
	public class Prealloc
	{
		private var _deployed:Array;
		private var _reserved:Array;
		private var _numDeployed:int;
		private var _maxAllowed:int;
		
		public function Prealloc(type:Class, amount:Number)
		{
			_deployed = new Array();
			_reserved = new Array();
			_maxAllowed = amount;
			_numDeployed = 0;
			
			for (var i:int = 0; i < amount; i++)
			{
				_reserved.push(new type());
			}
		}
		
		public function get deployed():Array
		{
			return _deployed;
		}
		
		public function getOne():IPreallocatable
		{
			if (_numDeployed == _maxAllowed)
			{
				throw new Error("You cannot get any more objects from the Prealloc. Max of " + _maxAllowed + ".");
				return;
			}
			
			_numDeployed++;
			var newOne:IPreallocatable = _reserved.shift();
			_deployed.push(newOne);
			newOne.deploy();
			return newOne;
		}
		
		public function killOne(value:IPreallocatable):void
		{
			var index:Number = _deployed.indexOf(value);
			
			if (index == -1)
			{
				throw new Error("The object you attempted to kill was not created by this Prealloc.");
				return;
			}
			_numDeployed--;
			_deployed.splice(index, 1);
			_reserved.push(value);
			value.reserve();
		}
	}
}